package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.annotations.Auth;
import cn.thoughtworks.school.entities.Serial;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.services.SerialService;
import cn.thoughtworks.school.services.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api/serials")
public class SerialController {

  @Autowired
  private SerialService serialService;

  @Autowired
  private VideoService videoService;

  @GetMapping("/my")
  public ResponseEntity getSerials(@Auth User user) {
    return ResponseEntity.ok(serialService.getSerialsByCreatorId(user.getId()));
  }

  @GetMapping("/users/subscriptions")
  public ResponseEntity getMySubscriptionSerials(@Auth User user) {
    return ResponseEntity.ok(serialService.getMySubscriptionSerials(user.getId()));
  }

  @GetMapping("/top")
  public ResponseEntity getTopSerials(@Auth User user) {
    return ResponseEntity.ok(serialService.getTopSerials(user.getId()));
  }

  @GetMapping("pageable")
  public ResponseEntity getPageableVideos(@Auth User user,
                                          @PageableDefault(value = 12) Pageable pageable) {
    return ResponseEntity.ok(serialService.getPageableVideosByOrganization(user.getId(), pageable));
  }

  @DeleteMapping("{id}")
  public ResponseEntity deleteSerial(@PathVariable Long id) throws BusinessException {
    serialService.deleteSerial(id);
    return ResponseEntity.noContent().build();
  }

  @PostMapping
  public ResponseEntity createSerial(@RequestBody Serial serial) {
    serial = serialService.createSerial(serial);

    return new ResponseEntity(serial, HttpStatus.CREATED);
  }

  @GetMapping("{id}")
  public ResponseEntity getSerial(@PathVariable Long id, @Auth User user) throws BusinessException {
    return ResponseEntity.ok(serialService.getSerial(id, user));
  }

  @PutMapping("{id}")
  public ResponseEntity editSerial(@PathVariable Long id,
                                   @RequestBody Serial serial) throws BusinessException {
    serial = serialService.editSerial(id, serial);

    return new ResponseEntity(serial, HttpStatus.NO_CONTENT);
  }

  @PutMapping("video/{videoId}")
  public ResponseEntity removeVideoFromSerial(@PathVariable Long videoId) throws BusinessException {
    videoService.removeVideoFromSerial(videoId);
    return ResponseEntity.ok(HttpStatus.NO_CONTENT);
  }


}
